package com.cdh.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdh.base.DIYException;
import com.cdh.edu.entity.Comment;
import com.cdh.edu.entity.Course;
import com.cdh.edu.entity.CourseCollect;
import com.cdh.edu.entity.CourseDescription;
import com.cdh.edu.entity.vo.*;
import com.cdh.edu.feign.OssFileService;
import com.cdh.edu.mapper.CourseMapper;
import com.cdh.edu.service.*;
import com.cdh.utils.result.Restful;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author cdh
 * @since 2020-10-20
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseDescriptionService courseDescriptionService;

    @Autowired
    private VideoService videoService;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private CourseCollectService courseCollectService;

    @Autowired
    private OssFileService ossFileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //1 向课程表添加课程基本信息
        Course c = new Course();
        //将courseInfoVo对象转换tCourse对象
        BeanUtils.copyProperties(courseInfoVo,c);
        c.setStatus(Course.COURSE_DRAFT);
        int insert = baseMapper.insert(c);
        if (insert == 0){
            throw new DIYException(201,"添加课程信息失败");
        }
        //获取添加之后的课程ID
        String cId = c.getId();

        // 2 向课程简介表添加课程简介
        CourseDescription tCourseDescription = new CourseDescription();
        tCourseDescription.setDescription(courseInfoVo.getDescription());
        tCourseDescription.setId(cId);
        courseDescriptionService.save(tCourseDescription);

        return cId;
    }

    // 根据课程ID查询课程基本信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CourseInfoVo getCourseInfo(String courseId) {
        //1 查询课程表
        Course tCourse = baseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(tCourse,courseInfoVo);

        //2 查询描述表
        CourseDescription courseDescription = courseDescriptionService.getById(courseId);
        courseInfoVo.setDescription(courseDescription.getDescription());

        return courseInfoVo;
    }

    //修改课程信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        //修改课程表
        Course tCourse = new Course();
        BeanUtils.copyProperties(courseInfoVo,tCourse);
        int update = baseMapper.updateById(tCourse);
        if (update == 0){
            throw new DIYException(201,"修改课程信息失败");
        }

        //修改描述表
        CourseDescription description = new CourseDescription();
        description.setId(courseInfoVo.getId());
        description.setDescription(courseInfoVo.getDescription());
        boolean b = courseDescriptionService.updateById(description);
        if (b == false){
            throw new DIYException(201,"修改课程描述信息失败");
        }
    }

    //根据课程id查询课程确认信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CoursePublishVo getPublishCourseInfoByCourseId(String courseId) {
        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(courseId);
        return publishCourseInfo;
    }

    //删除课程
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCourseById(String courseId) {
        // 根据课程id删除小节
        videoService.deleteVideoByCourseId(courseId);

        // 根据课程id删除章节
        chapterService.deleteChapterById(courseId);

        // 根据课程id删除课程描述
        courseDescriptionService.removeById(courseId);

        //TODO:删除评论
        QueryWrapper<Comment> comment = new QueryWrapper<>();
        comment.eq("course_id", courseId);
        commentService.remove(comment);

        //TODO:删除课程收藏
        QueryWrapper<CourseCollect> collect = new QueryWrapper<>();
        collect.eq("course_id", courseId);
        courseCollectService.remove(collect);

        // 根据课程id删除整个课程
        int res = baseMapper.deleteById(courseId);
        if (res == 0){
            throw new DIYException(201,"删除课程失败！");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IPage<CourseVo> selectPage(long current, long limit, CourseQueryVo cq) {
        //组装查询条件
        QueryWrapper<CourseVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("c.gmt_create");
        String title = cq.getTitle();
        String teacherId = cq.getTeacherId();
        String subjectId = cq.getSubjectId();
        String subjectParentId = cq.getSubjectParentId();

        if (!StringUtils.isEmpty(title)){
            queryWrapper.like("c.title",title);
        }

        if (!StringUtils.isEmpty(teacherId)){
            queryWrapper.eq("c.teacher_id",teacherId);
        }

        if (!StringUtils.isEmpty(subjectParentId)){
            queryWrapper.ge("c.subject_parent_id",subjectParentId);
        }

        if (!StringUtils.isEmpty(subjectId)){
            queryWrapper.le("c.subject_id",subjectId);
        }
        //组装分页
        Page<CourseVo> courseVoPage = new Page<>(current, limit);
        //执行分页查询 只需要在mapper层传入封装好的分页组件即可，sql分页条件的组装的过程由mp自动完成
        List<CourseVo> records = baseMapper.selectPageByCourseVo(courseVoPage,queryWrapper);
        return courseVoPage.setRecords(records);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCoverById(String id) {
        Course course = baseMapper.selectById(id);
        if (course != null){
            String cover = course.getCover();
            if (!StringUtils.isEmpty(cover)){
                // oss删除头像的方法
                Restful restful = ossFileService.removeFileAvatar(cover);
                return restful.getSuccess();
            }
        }
        return false;
    }

    @Override
    public List<Course> webSelectList(WebCourseQueryVo webCourseQueryVo) {
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        // 查询已发布的课程
        courseQueryWrapper.eq("status", Course.COURSE_NORMAL);

        if (!StringUtils.isEmpty(webCourseQueryVo.getSubjectParentId())){
            courseQueryWrapper.eq("subject_parent_id", webCourseQueryVo.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(webCourseQueryVo.getSubjectId())){
            courseQueryWrapper.eq("subject_id", webCourseQueryVo.getSubjectId());
        }

        if (!StringUtils.isEmpty(webCourseQueryVo.getBuyCountSort())){
            courseQueryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(webCourseQueryVo.getGmtCreateSort())){
            courseQueryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(webCourseQueryVo.getPriceSort())){
            if (webCourseQueryVo.getType() == null || webCourseQueryVo.getType() == 1){
                courseQueryWrapper.orderByAsc("price");
            }else {
                courseQueryWrapper.orderByDesc("price");
            }
        }
        return baseMapper.selectList(courseQueryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WebCourseVo selectWebCourseVoById(String id) {
        Course course = baseMapper.selectById(id);
        // 更新浏览数
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);

        // 获取课程信息
        return baseMapper.selectWebCourseVoById(id);
    }

    @Cacheable(value = "index",key = "'selectHotCourse'")
    @Override
    public List<Course> selectHotCourse() {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("view_count");
        queryWrapper.last("limit 8");
        return baseMapper.selectList(queryWrapper);
    }
}
